package com.jianan.mis.app.overseastudy;

import static com.jianan.mis.util.ui.table.TableCreator.createTableColumn;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.part.ViewPart;

import com.jianan.mis.data.cache.CountryCache;
import com.jianan.mis.data.cache.EmployeeCache;
import com.jianan.mis.data.dao.base.PageControl;
import com.jianan.mis.data.domain.Country;
import com.jianan.mis.data.domain.Employee;
import com.jianan.mis.data.domain.OsContract;
import com.jianan.mis.data.domain.OsContractState;
import com.jianan.mis.data.domain.Session;
import com.jianan.mis.service.OsContractService;
import com.jianan.mis.sys.IGroupKeys;
import com.jianan.mis.sys.IImageKeys;
import com.jianan.mis.sys.IMessageKeys;
import com.jianan.mis.sys.ImageManager;
import com.jianan.mis.sys.ResourceManager;
import com.jianan.mis.sys.SpringBeanFactory;
import com.jianan.mis.util.StringUtils;

public class FinishedOsContractArchiveView extends ViewPart {

	private Label lblResult;
	private Label lblPage;
	private Combo comboVisaResult;
	private Text txtStudentName;
	private Text txtContractNo;
	private Combo comboCountry;
	
	class TableLabelProvider extends LabelProvider implements ITableLabelProvider {
		public String getColumnText(Object element, int columnIndex) {
			OsContract osContract = (OsContract) element;
			String text = contracts.getColumn(columnIndex).getText();
			if (text.equals(CONTRACT_ID)) {
				return osContract.getId().toString();
			} else if (text.equals(CONTRACT_NO)) {
				return osContract.getContractNo();
			} else if (text.equals(STUDENT_NAME)) {
				return osContract.getName();
			} else if (text.equals(STUDENT_BIRTHDAY)) {
				return dateFormat.format(osContract.getBirthday());
			} else if (text.equals(COUNTRY_NAME)) {
				return osContract.getCountryIntent().getName();
			} else if (text.equals(INTENT1)) {
				return osContract.getIntent1();
			} else if (text.equals(INTENT2)) {
				return osContract.getIntent2();
			} else if (text.equals(INTENT3)) {
				return osContract.getIntent3();
			} else if (text.equals(CONSULTANT_NAME)) {
				if (osContract.getConsultant() != null)
					return osContract.getConsultant().getName();
				else
					return "";
			} else if (text.equals(MATERIALMAN_NAME)) {
				return osContract.getMaterialman().getName();
			} else if (text.equals(INTERMAN_NAME)) {
				if(osContract.getInterman() != null)
					return osContract.getInterman().getName();
				else
					return "";
			} else if (text.equals(VISA_RESULT)) {
				return osContract.getVisaResult();
			} else if (text.equals(STATE)) {
				if (osContract.getState().equals(OsContractState.FINISHED))
					return "已结案";
				else
					return "合同废除";
			} else {
				return null;
			}
		}
		public Image getColumnImage(Object element, int columnIndex) {
			return null;
		}
	}
	class ContentProvider implements IStructuredContentProvider {
		public Object[] getElements(Object inputElement) {
			return ((List) inputElement).toArray();
		}
		public void dispose() {
		}
		public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
		}
	}
	
	public static final String ID = "com.jianan.mis.app.overseastudy.FinishedOsContractArchiveView"; //$NON-NLS-1$

	private TableViewer contractTableViewer;
	private Table contracts;
	final private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy年MM月dd日");
	final private int PAGE_SIZE = 15;
	private PageControl pageControl;
	private Map conditions;

	/**
	 * Create contents of the view part
	 * @param parent
	 */
	@Override
	public void createPartControl(Composite parent) {
		final FillLayout fillLayout = new FillLayout();
		fillLayout.marginWidth = 10;
		fillLayout.marginHeight = 10;
		parent.setLayout(fillLayout);
		Composite container = new Composite(parent, SWT.NONE);
		final GridLayout gridLayout = new GridLayout();
		gridLayout.makeColumnsEqualWidth = true;
		gridLayout.numColumns = 4;
		container.setLayout(gridLayout);

		final Label label = new Label(container, SWT.NONE);
		label.setFont(ResourceManager.getFont("", 10, SWT.BOLD));
		label.setText("查询条件:");
		new Label(container, SWT.NONE);
		new Label(container, SWT.NONE);
		new Label(container, SWT.NONE);

		final Label label_1 = new Label(container, SWT.NONE);
		label_1.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false));
		label_1.setText("学生姓名:");

		txtStudentName = new Text(container, SWT.BORDER);
		final GridData gd_txtStudentName = new GridData(SWT.LEFT, SWT.CENTER, true, false);
		gd_txtStudentName.widthHint = 120;
		txtStudentName.setLayoutData(gd_txtStudentName);

		final Label label_2 = new Label(container, SWT.NONE);
		label_2.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false));
		label_2.setText("国家:");

		comboCountry = new Combo(container, SWT.READ_ONLY);
		final GridData gd_comboCountry = new GridData(SWT.LEFT, SWT.CENTER, true, false);
		comboCountry.setLayoutData(gd_comboCountry);

		final Label label_4 = new Label(container, SWT.NONE);
		label_4.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false));
		label_4.setText("合同号:");

		txtContractNo = new Text(container, SWT.BORDER);
		final GridData gd_txtContractNo = new GridData(SWT.LEFT, SWT.CENTER, true, false);
		gd_txtContractNo.widthHint = 148;
		txtContractNo.setLayoutData(gd_txtContractNo);

		final Label label_5 = new Label(container, SWT.NONE);
		label_5.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false));
		label_5.setText("签证结果:");

		comboVisaResult = new Combo(container, SWT.READ_ONLY);
		comboVisaResult.setItems(new String[] {"获签", "拒签"});
		final GridData gd_comboVisaResult = new GridData(SWT.LEFT, SWT.CENTER, true, false);
		comboVisaResult.setLayoutData(gd_comboVisaResult);
		
		new Label(container, SWT.NONE);

		final Button btnQuery = new Button(container, SWT.NONE);
		btnQuery.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(final SelectionEvent e) {
				pageControl = new PageControl(PAGE_SIZE);
				buildQueryConditions();
				pageQuery();
			}
		});
		final GridData gd_btnQuery = new GridData(SWT.CENTER, SWT.CENTER, false, false);
		btnQuery.setLayoutData(gd_btnQuery);
		btnQuery.setText("查询");
		btnQuery.setImage(ImageManager.getImage(IImageKeys.SEARCH));

		final Button btnReset = new Button(container, SWT.NONE);
		btnReset.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(final SelectionEvent e) {
				txtStudentName.setText("");
				comboCountry.deselectAll();
				txtContractNo.setText("");
				comboVisaResult.deselectAll();
			}
		});
		final GridData gd_btnReset = new GridData(SWT.CENTER, SWT.CENTER, false, false);
		btnReset.setLayoutData(gd_btnReset);
		btnReset.setText("重置");
		btnReset.setImage(ImageManager.getImage(IImageKeys.RESET));

		final Label label_7 = new Label(container, SWT.NONE);
		label_7.setFont(ResourceManager.getFont("", 10, SWT.BOLD));
		label_7.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 4, 1));
		label_7.setText("查询结果:");
		
		new Label(container, SWT.NONE);
		new Label(container, SWT.NONE);
		
		lblResult = new Label(container, SWT.NONE);
		lblResult.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false));
		lblResult.setText("");

		lblPage = new Label(container, SWT.NONE);
		lblPage.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false));
		lblPage.setText("");		
		
		final Button btnFirstPage = new Button(container, SWT.NONE);
		btnFirstPage.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(final SelectionEvent e) {
				if (pageControl == null) {
					MessageDialog.openInformation(e.display.getActiveShell(),
							IMessageKeys.FAIL, "请先进行查询!");
					return;
				}
				if (pageControl.getPageCount() > 0) {
					pageControl.setPageNo(1);
					pageQuery();
				}
			}
		});
		final GridData gd_btnFirstPage = new GridData(SWT.RIGHT, SWT.CENTER, false, false);
		btnFirstPage.setLayoutData(gd_btnFirstPage);
		btnFirstPage.setText("首页");
		btnFirstPage.setImage(ImageManager.getImage(IImageKeys.LEFT));

		final Button btnPrevPage = new Button(container, SWT.NONE);
		btnPrevPage.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(final SelectionEvent e) {
				if (pageControl == null) {
					MessageDialog.openInformation(e.display.getActiveShell(),
							IMessageKeys.FAIL, "请先进行查询!");
					return;
				}
				if (pageControl.getPageNo() - 1 > 0) {
					pageControl.setPageNo(pageControl.getPageNo() - 1);
					pageQuery();
				}
			}
		});
		final GridData gd_btnPrevPage = new GridData(SWT.CENTER, SWT.CENTER, false, false);
		btnPrevPage.setLayoutData(gd_btnPrevPage);
		btnPrevPage.setText("上页");
		btnPrevPage.setImage(ImageManager.getImage(IImageKeys.UP));

		final Button btnNextPage = new Button(container, SWT.NONE);
		btnNextPage.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(final SelectionEvent e) {
				if (pageControl == null) {
					MessageDialog.openInformation(e.display.getActiveShell(),
							IMessageKeys.FAIL, "请先进行查询!");
					return;
				}
				if (pageControl.getPageNo() + 1 <= pageControl.getPageCount()) {
					pageControl.setPageNo(pageControl.getPageNo() + 1);
					pageQuery();
				}
			}
		});
		btnNextPage.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, false, false));
		btnNextPage.setText("下页");
		btnNextPage.setImage(ImageManager.getImage(IImageKeys.DOWN));

		final Button btnLastPage = new Button(container, SWT.NONE);
		btnLastPage.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(final SelectionEvent e) {
				if (pageControl == null) {
					MessageDialog.openInformation(e.display.getActiveShell(),
							IMessageKeys.FAIL, "请先进行查询!");
					return;
				}
				if (pageControl.getPageCount() > 0) {
					pageControl.setPageNo(pageControl.getPageCount());
					pageQuery();
				}
			}
		});
		btnLastPage.setLayoutData(new GridData());
		btnLastPage.setText("尾页");
		btnLastPage.setImage(ImageManager.getImage(IImageKeys.RIGHT));

		contractTableViewer = new TableViewer(container, SWT.FULL_SELECTION | SWT.BORDER);
		contractTableViewer.setLabelProvider(new TableLabelProvider());
		contractTableViewer.setContentProvider(new ContentProvider());
		contracts = contractTableViewer.getTable();
		contracts.setLinesVisible(true);
		contracts.setHeaderVisible(true);
		final GridData gd_table = new GridData(SWT.FILL, SWT.FILL, true, true, 4, 1);
		gd_table.heightHint = 150;
		contracts.setLayoutData(gd_table);
		
		initializeTableViewer();
		initializeServices();
		setupValues();
		filterPermission();
		notice();
		
		//
		createActions();
		initializeToolBar();
		initializeMenu();
	}
	
	public static final String CONTRACT_ID = "签约档案号";
	public static final String CONTRACT_NO = "合同号";
	public static final String STUDENT_NAME = "签约学生";
	public static final String STUDENT_BIRTHDAY = "出生年月日";
	public static final String COUNTRY_NAME = "签约国家";
	public static final String INTENT1 = "申请院校1";
	public static final String INTENT2 = "申请院校2";
	public static final String INTENT3 = "申请院校3";
	public static final String CONSULTANT_NAME = "咨询员";
	public static final String MATERIALMAN_NAME = "材料员";
	public static final String INTERMAN_NAME = "中间人";
	public static final String DEPARTMENT = "部门";
	public static final String VISA_RESULT = "签证结果";
	public static final String STATE = "状态";
	
	private void initializeTableViewer() {
		//createTableColumn(contractTableViewer, SWT.CENTER, CONTRACT_ID, "", 100, null);
		createTableColumn(contractTableViewer, SWT.CENTER, CONTRACT_NO, "", 100, null);
		createTableColumn(contractTableViewer, SWT.CENTER, STUDENT_NAME, "", 100, null);
		createTableColumn(contractTableViewer, SWT.CENTER, STUDENT_BIRTHDAY, "", 100, null);
		createTableColumn(contractTableViewer, SWT.CENTER, COUNTRY_NAME, "", 100, null);
		createTableColumn(contractTableViewer, SWT.CENTER, INTENT1, "", 150, null);
		createTableColumn(contractTableViewer, SWT.CENTER, INTENT2, "", 150, null);
		createTableColumn(contractTableViewer, SWT.CENTER, INTENT3, "", 150, null);
		createTableColumn(contractTableViewer, SWT.CENTER, CONSULTANT_NAME, "", 100, null);
		createTableColumn(contractTableViewer, SWT.CENTER, MATERIALMAN_NAME, "", 100, null);
		createTableColumn(contractTableViewer, SWT.CENTER, INTERMAN_NAME, "", 100, null);
		createTableColumn(contractTableViewer, SWT.CENTER, DEPARTMENT, "", 100, null);
		createTableColumn(contractTableViewer, SWT.CENTER, VISA_RESULT, "", 100, null);
		createTableColumn(contractTableViewer, SWT.CENTER, STATE, "", 100, null);
	}
	
	List<Integer> materialmanIds = new ArrayList<Integer>();
	List<Integer> countryIds = new ArrayList<Integer>();
	
	private void setupValues() {
		List<Employee> consultants = EmployeeCache.getInstance().getEmployeesByGroups(
				new String[] { IGroupKeys.OSMATERIALMAN, IGroupKeys.OSMATERIALCHIEF });
		if (consultants != null) {
			for (Employee employee : consultants) {
				materialmanIds.add(employee.getId());
			}
		}
		List<Country> countries = CountryCache.getInstance().getAllCountries();
		if (countries != null) {
			for (Country country : countries) {
				countryIds.add(country.getId());
				comboCountry.add(country.getName());
			}
		}
	}
	
	private void filterPermission() {
		if (!Session.getInstance().getGroups().contains(IGroupKeys.FIN_DEP)
				&& !Session.getInstance().getGroups().contains(IGroupKeys.MANAGER)) {
		}
	}
	
	private void notice() {
	}
	
	@SuppressWarnings("unchecked")
	private void buildQueryConditions() {
		conditions = new HashMap();
		if (StringUtils.isNotEmpty(txtStudentName.getText())) {
			conditions.put("studentName", txtStudentName.getText().trim());
		}
		if (comboCountry.getSelectionIndex() >= 0) {
			conditions.put("countryId", countryIds.get(comboCountry.getSelectionIndex()));
		}
		if (StringUtils.isNotEmpty(txtContractNo.getText())) {
			conditions.put("contractNo", txtContractNo.getText().trim());
		}
		conditions.put("finishedStates", true);
		if (comboVisaResult.getSelectionIndex() == 0) {
			conditions.put("visaResult", "获签");
		} else if (comboVisaResult.getSelectionIndex() == 1) {
			conditions.put("visaResult", "拒签");
		}
	}
	
	private void pageQuery() {
		osContractService.pageQuery(pageControl, conditions);
		contractTableViewer.setInput(pageControl.getPageData());
		lblResult.setText("查询结果共 " + pageControl.getRowCount() + " 条记录");
		lblPage.setText("页码(每页显示" + PAGE_SIZE + "条): " + pageControl.getPageNo() + "/" + pageControl.getPageCount());
		contracts.deselectAll();
	}

	private OsContractService osContractService;
	
	private void initializeServices() {
		osContractService = (OsContractService) SpringBeanFactory.getBean("osContractService");
	}

	/**
	 * Create the actions
	 */
	private void createActions() {
		// Create the actions
	}

	/**
	 * Initialize the toolbar
	 */
	private void initializeToolBar() {
	}

	/**
	 * Initialize the menu
	 */
	private void initializeMenu() {
	}

	@Override
	public void setFocus() {
		// Set the focus
	}
}
